package com.tsystems.train.security;

import java.io.IOException;

import javax.inject.Inject;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tsystems.train.bean.UserBean;
import com.tsystems.train.entity.UserRoles;

@WebFilter(urlPatterns = "/*")
public class SecurityFilter implements Filter {
	@Inject
	private UserBean userBean;

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws ServletException, IOException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String url = req.getRequestURL().toString();

		if (url.contains("javax.faces.resource")) {
			chain.doFilter(request, response);
		} else if (userBean != null && userBean.isLoggedIn()) {

			if ((!userBean.getRole().equals(UserRoles.EMPLOYEE.toString()))
					&& (url.endsWith("train-web/userTable")
							|| url.endsWith("train-web/trainTable") || url
								.endsWith("train-web/stationTable"))) {
				res.sendRedirect(req.getContextPath() + "/");
			} else {
				chain.doFilter(request, response);
			}
			
		} else {
			if (url.endsWith("train-web/userTable")
					|| url.endsWith("train-web/trainTable")
					|| url.endsWith("train-web/stationTable")
					|| url.endsWith("train-web/myTickets")
					|| url.endsWith("train-web/buyTicket")) {
				res.sendRedirect(req.getContextPath() + "/");
				
			} else {
				chain.doFilter(request, response);
			}
		}
	}

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}
}
